package main

import (
	"time"
	"encoding/json"
)

type Result struct {
	Cost   int        `json:"cost_ms"`
	Value interface{} `json:"value,omitempty"`
	code  int
	err    error
	start  int64
	action Action
}

type Action string

const (
	POST = Action("post")
	GET  = Action("get")
)

func NewResult() *Result {
	return &Result{start: time.Now().UnixNano()}
}

func (r *Result) Finish() *Result {
	r.Cost = int((time.Now().UnixNano() - r.start) / 1000 / 1000)
	if r.Value == nil && r.err != nil {
		r.Value = r.err
	}
	return r
}

func (r *Result) WithAction(act Action) *Result {
	r.action = act
	return r
}

func (r *Result) WithError(err error) *Result {
	r.err = err
	return r
}

func (r *Result) WithValue(value interface{}) *Result {
	r.Value = value
	return r
}

func (r *Result) WithCode(code int) *Result {
	r.code = code
	return r
}

func (r *Result) bytes() []byte {
	b, _ := json.Marshal(r)
	return b
}

func (r *Result) String() (ret string) {
	b, _ := json.Marshal(r)
	ret = string(b)
	return
}
